package com.xiaoxu.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.bbs.common.ReturnResults;
import com.xiaoxu.bbs.entity.Reply;
import com.xiaoxu.bbs.service.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/reply")
public class ReplyController {
    @Autowired
    private ReplyService replyService;

    @GetMapping("/count/{topicId}")
    public ReturnResults getReplyCount(@PathVariable Long topicId) {
        if (topicId != null) {
            LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Reply::getTopicId, topicId);
            List<Reply> list = replyService.list(queryWrapper);
            if (list != null) {
                return ReturnResults.success(list.size());
            }
        }
        return ReturnResults.error("请检查主题ID是否是正确的!");
    }

    @GetMapping("/{topicId}")
    public ReturnResults getReplyInfo(@PathVariable Long topicId, Integer page, Integer pageSize,HttpSession session) {
        session.setAttribute("topicId",topicId);
        if (page != null && pageSize != null) {
            Page<Reply> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(topicId != null, Reply::getTopicId, topicId);
            replyService.page(pageInfo, queryWrapper);
            return ReturnResults.success(pageInfo);
        }
        return ReturnResults.error("业务出异常了，请向工作人员反馈!");
    }

    @PostMapping("/add")
    public ReturnResults saveReply(@RequestBody Reply reply, HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        Long topicId = (Long) session.getAttribute("topicId");
        reply.setUserId(userId);
        if (reply.getRereplyId() != null && reply.getId() == null){
            reply.setTopicId(topicId);
        }
        replyService.save(reply);
        return ReturnResults.success("回复成功！");
    }

    @PostMapping("/edit")
    public ReturnResults editReply(@RequestBody Reply reply){
        replyService.updateById(reply);
        return ReturnResults.success("修改成功!");
    }

    @GetMapping("/delete/{replyId}")
    public ReturnResults deleteReplyById(@PathVariable Long replyId,HttpSession session){
        Long topicId = (Long) session.getAttribute("topicId");
        Boolean res = replyService.deleteReplyWithItReplys(replyId,topicId);
        return res?ReturnResults.success("删除成功!"):ReturnResults.error("删除失败，请联系管理人员");

    }
}
